package com.xy.blog.core.utils;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.bouncycastle.util.encoders.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

/**
 * @author zanhonglei
 * @version V1.0
 * @Description:
 * @date 2020/5/30
 */
public class AESUtil {

    private static final Logger logger = LoggerFactory.getLogger(AESUtil.class);

    private static String Algorithm = "AES";

    private static String AlgorithmProvider = "AES/ECB/PKCS5Padding"; // 算法/模式/补码方式

    /**
     * 加密
     * @param src
     * @param key
     * @return
     */
    public static String encrypt(String src, String key) {
        try {
            SecretKey secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), Algorithm);
            //IvParameterSpec ivParameterSpec = getIv();
            Cipher cipher = Cipher.getInstance(AlgorithmProvider);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            byte[] cipherBytes = cipher.doFinal(src.getBytes(StandardCharsets.UTF_8));
            return Base64.toBase64String(cipherBytes);
        } catch (Exception e) {
            logger.error(ExceptionUtils.getStackTrace(e));
        }
        return src;
    }

    /**
     * 解密
     * @param src
     * @param key
     * @return
     */
    public static String decrypt(String src,String key) {
        try {
            SecretKey secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), Algorithm);

            //IvParameterSpec ivParameterSpec = getIv();
            Cipher cipher = Cipher.getInstance(AlgorithmProvider);
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            byte[] plainBytes = cipher.doFinal(Base64.decode(src.getBytes(StandardCharsets.UTF_8)));
            return new String(plainBytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            logger.error(ExceptionUtils.getStackTrace(e));
        }
        return src;
    }

}

